<template>
  <div class="form-text flex">
    <form-text
      :field="field"
      @input="inputEvent"
      @focus="handlerInputFocus"
      :placeholder="placeholder || placeholderText"
      :value="value"
      @blur="handlerInputBlur"/>
      <!-- <template -->
        <!-- v-if="idCardOcrCheckData.identityCardMargin <= 0"> -->
        <el-popover
        placement="top"
        ref="elPopover"
        trigger="manual"
        v-model="showPopover"
       >
        <div class="el-popover-confirm__box">
          <div class="title">
            <i class="el-icon-warning"></i>
            <span class="text">
							{{ $t('customer.idCard.tipTitle3')}}
						</span>
          </div>
          <div class="button">
            <el-button size="mini" plain @click="showPopover = false">{{  $t('common.base.cancel') }}</el-button>
            <el-button size="mini" type="primary" @click="handleElPopoverConfirm">
              <template v-if="checkIdCardOcrStatus.systemAdmin">
								{{ $t('customer.idCard.goRecharge')}}
              </template>
              <template v-else>
                {{ $t('common.base.remind') }}
              </template>
            </el-button>
          </div>
        </div>
        <el-button slot="reference" icon="iconfont icon-renlianxinxi" class="identity-btn" type="text" :disabled="pending" @click="handleUpload">
          <template v-if="pending">
						{{ $t('customer.idCard.identifying')}}
          </template>
          <template v-else>
						{{ $t('customer.idCard.iDIdentification')}}
          </template>
        </el-button>
      </el-popover>
      <!-- </template> -->
      <!-- <el-button v-else slot="reference" class="identity-btn" type="plain-third" @click="handleUpload">证件识别</el-button> -->
      <!-- <base-upload 
        class="identity-upload"
        @input="input" 
        accept="image/*" 
        :value="[]" 
        :limit="2" 
        :for-id="`form_${field.fieldName}`" 
       /> -->
   
       <!-- <base-modal :show="showModal" title="提醒">

        <div slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </div>
      </base-modal> -->
      <tip-modal :type="tipModalType" ref="tipModal" @handleConfirm="handleModalConfirm"/>
      
      <input type="file" ref="input" @change="handleChange" :multiple="true" accept="image/jpeg,image/png">
  </div>
</template>

<script>
// TODO  多语言支持

/** mixin */
import FormMixin from '@src/component/form/mixin/form';
/** const */
import { FORM_FIELD_TEXT_MAX_LENGTH } from '@src/model/const/Number.ts';
/** utils */
import Uploader from '@src/util/uploader';
import { genPlaceholder} from '../../util'
import platform from '@src/platform';
/** api */
import { getWorkbenchIdCardOcr, getWorkbenchIdCardOrcCheck, fetchWorkbenchRemind } from '@src/api/WorkbenchApi'
/** enum */
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum'
import { ModalType } from './components/TipModal/TipModal'
import TipModal from './components/TipModal/TipModal'

export default {
  name: 'form-identity',
  mixins: [FormMixin],
  components: {
    TipModal
  },
  props: {
    value: {
      type: String, 
      default: ''
    }
  },
  data() {
    return {
      // 是否是输入中文
      $isInputZh: false,
      maxlength: FORM_FIELD_TEXT_MAX_LENGTH,
      placeholderText: '',
      pending: false,
      showPopover: false,
      showModal: true,
      remindValue: '',
      tipModalType: ModalType.Tip,
      checkIdCardOcrStatus: {
        systemAdmin: false,
        identityCardMargin: 0
      }
    }
  },
  computed: {
    /** 相关身份控件的身份证照片控件field */
    idCardAttachmentField() {
      return this.checkedFields.find(field=> field?.setting?.parentFormType === FieldTypeMappingEnum.IdCard && field.formType === FieldTypeMappingEnum.Attachment)|| ''
    },
    checkedFields() {
      const parentFieldName = this.field?.setting?.parentFieldName
      const subFields = this.fields.find(field => field.fieldName === parentFieldName)?.setting.settingFields || []
      return subFields.filter(field=> field.setting.show)
    }
  },
  watch: {
    field: {
      handler(newValue) {
        this.placeholderText = genPlaceholder(this.field);
      },
      immediate: true
    }
  },
  methods: {
    /**
     * 描述 请求发送提醒消息
     * @date 2022-12-02
     * @param {any} value
     * @returns {any}
     */
    async handleModalConfirm(value) {
      const rs = await fetchWorkbenchRemind({messageTypes: [ value ]}).catch(err => console.error('[fetch fetchWorkbenchRemind error]',err))
      if(rs?.succ) {
        this.$refs.tipModal.closeDialog()
        this.$message.success(this.$t('customer.idCard.reminderSent'))
      } else {
        this.$message.error(rs.message)
      }
    },
    
    handleElPopoverConfirm() {
      this.handleClosePopover()
      const title = this.checkIdCardOcrStatus.systemAdmin ? this.$t('customer.idCard.recharge') : this.$t('common.base.remind')
      this.$refs.tipModal.handleShowModal({ title })
    },
    /**
     * 描述 判断ocr对应的余量
     * @date 2022-12-02
     * @returns {any}
     */
    async fetchIdCardOcrCheckValue() {
      const rs = await getWorkbenchIdCardOrcCheck()
      .catch(err=> console.error('[fetch getWorkbenchIdCardOrcCheck error]', err))
      const reusltStatus = rs?.data || {}
      this.tipModalType = reusltStatus?.systemAdmin ? ModalType.Recharge : ModalType.Tip
      this.checkIdCardOcrStatus = reusltStatus
      return reusltStatus
    },
    /**
     * 描述 相关图片上传操作change事件
     * @date 2022-11-30
     * @param {any} event
     * @returns {any}
     */
    handleChange(event) {
      const files = event.target.files;
      if(!files || !files.length) return;
      const attachmentValue = this.formValue[this.idCardAttachmentField.fieldName]
			let num = 2
      if(Array.isArray(attachmentValue) && (attachmentValue.length + files.length > num)) return this.$message.warning(this.$t('customer.idCard.uploadNumMax', {num}))
			let max = 1
      if(this.checkIdCardOcrStatus.identityCardMargin === 1 && files.length > max) return this.$message.warning(this.$t('customer.idCard.selectNumMax', {max}))
      this.pending = true
      Uploader.batchUploadWithParse({files})
      .then(async (result) =>{
        const { success = [], error = [] } = result;
        if( error && error.length > 0){
          let message = error.map(item => item.message).join('\n');
          platform.alert(message)
        }

        this.$refs.input.value = ''
        // 上传成功了更新对应身份照片控件值
        if(this.idCardAttachmentField) {
          const attachmentValue = this.formValue[this.idCardAttachmentField.fieldName]
          const defaultAttachment = attachmentValue ? attachmentValue : []
          this.$emit('update', {newValue: [...success, ...defaultAttachment], oldValue: [], field: this.idCardAttachmentField});
        }
        // 请求对应身份证识别api
        await this.fetchIdCardOrc(success)
      })
      .catch(err => console.error(err))
      .finally(() => this.pending = false)
    },
    /**
     * 描述 请求相关ocr接口识别
     * @date 2022-11-30
     * @param {any} fileArr
     * @returns {any}
     */
    async fetchIdCardOrc(fileArr) {
      if(fileArr.length === 0) return 
      const urls = fileArr.map(item=> item.url)
      const rs = await getWorkbenchIdCardOcr({urls, event: this.formBuilderComponent.mode })
      if(rs && rs.succ) {
        const { data } = rs
        const checkedFields = this.checkedFields
        for(let [k, v] of Object.entries(data)){
          const index = checkedFields.findIndex(field => field.fieldName.includes(k))
          if(index > -1 && v) {
            const checkedField = checkedFields[index]
            this.$emit('update', { newValue: v, oldValue: null, field: checkedField });
          }
        }
      } else {
        this.$message.error(rs.message)
      }
    },
    /**
     * 描述 点击上传事件
     * @date 2022-11-30
     * @returns {any}
     */
    async handleUpload() {
      const rs = await this.fetchIdCardOcrCheckValue()
      if(!rs?.identityCardMargin || rs?.identityCardMargin <=0) {
        this.showPopover = true
      } else {
        this.$refs.input.click()
      }
    },
    handleClosePopover() {
      this.$refs.elPopover?.doClose()
    },
    inputEvent(value) {
      this.inputForValue(value)
    },
    handlerInputFocus() {
      this.$emit('focus')
    },
    handlerInputBlur() {
      this.$emit('blur', 'input')
    }
  },
  mounted() {
    document.body.addEventListener('click', ()=> {
      this.handleClosePopover()
    }, false)
  },
  beforeDestroy() {
    document.body.removeEventListener(()=> {}, null)
  }
}
</script>

<style lang="scss" scoped>
.form-text{
  width: 100%;
  .identity-btn{
    margin-left: 6px;
    flex-shrink: 0;
  }
  input[type="file"]{
    display: none;
  }
  .identity-upload{
    margin-left: 6px;
    flex-shrink: 0;
    ::v-deep .btn{
      background: #F5F8FA !important;
      border-radius: 4px;
      border: 1px solid #CBD6E2 !important;
      display: flex;
      &:hover{
        color:  $color-primary !important;
        background-color: #F5F8FA !important;
        border-color:  $color-primary !important;
        span {
          color: $color-primary
        }
      }
      .iconfont{
        color: $color-primary;
        font-size: 14px;
        width: 14px;
        height: 14px;
        line-height: 14px;
      }
      span {
        color: #595959;
        font-size: 14px;
      }
    }
  }
}
.el-popover-confirm__box{
   .title{
      display: flex;
      /* align-items: center; */
      i{
        display: block;
        width: 20px;
        color: #FAAD14;
      }
      .text{
        display: block;
        font-size: 14px;
        font-weight: 400;
        color: #595959;
        line-height: 22px;
        width:182px;
      }
    }
    .button{
        display: flex;
        justify-content:flex-end;
        margin-top: 10px;
        button{
          border-radius: 3px;
        }
      }
  }
  .form-text {
    --input-btn-max-width: 77px;
    --input-btn-margin-left: 10px;
    --input-right: 10px;
    --input-icon-width: 25px;
    --input-icon-right: calc(var(--input-btn-max-width) + var(--input-right));
    --input-padd-right: calc(var(--input-icon-right) + var(--input-icon-width));
    --input-tag-right: var(--input-padd-right);
    .form-text {
      input {
        padding-right: var(--input-padd-right);
      }
      .el-input__suffix {
        right: var(--input-icon-right);
      }
    }
    position: relative;
    button {
      position: absolute;
      right: var(--input-right);
      top: 50%;
      transform: translateY(-50%);
      // 这里不需要隐藏因为这里有长度限制
      // max-width: var(--input-btn-max-width);
      // overflow: hidden;
      // white-space: nowrap;
      // text-overflow: ellipsis;
    }
  }
</style>
